package 补充.网络编程;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.channels.Pipe;
class TestThread implements Runnable{
    private Socket client=null;
    public TestThread(Socket client) {
        this.client=client;
    }
    @Override
    public void run() {
        BufferedReader br=null;
        PrintStream ps=null;
        try {
            br=new BufferedReader(new InputStreamReader(client.getInputStream()));
            ps=new PrintStream(client.getOutputStream());
            boolean flag=true;
            while(flag){
                String str=br.readLine();
                if(str==null||"".equals(str)){  //判断的是 str 为 null 或者为空字符串的情况
                    flag=false;
                }else {
                    System.out.println(str);
                    if("bye".equals(str)){
                        flag=false;
                    }else {
                        ps.println("服务端已收到");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {

            if(ps!=null){
                ps.close();
            }

            if(client!=null){
                try {
                    client.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }

        }
    }
}
public class 多线程的TCP网络程序服务端 {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(9191);
        Socket socket = null;
        boolean flag=true;
        while(flag){
            System.out.println("等待接收数据");
            socket=serverSocket.accept();
            new Thread(new TestThread(socket)).start();
        }
        serverSocket.close();
    }
}
